<?php
declare(strict_types=1);

namespace hec;

use app\library\facade\Logger;
use hec\core\Applets;

class Client
{
    private $bind = [
        'store_list' => 'getStoreList',
        'invoice_list'=> 'getInvoiceList'
    ];

    public function send(string $method, array $data){
        if (!isset($this->bind[$method])) {
            throw new HecException('方法不存在');
        }
        $this->logInfo("hec:{$method}:request", $data);
        try {
            $response = call_user_func([(new Applets()), $this->bind[$method]], $data);
        } catch (\Exception $e){
            $this->logError("hec:{$method}:{$e->getMessage()}", ['param'=>$data]);
            throw new HecException($e->getMessage());
        }
        $this->logInfo("hec:{$method}:response", $response);
        if ($response['code'] != 10000) {
            $this->logError("hec:{$method}:{$response['msg']}", ['param'=>$data]);
            throw new HecException($response['msg']);
        }
        return $response['data'];
    }

    private function logInfo(string $message, array $context)
    {
        $this->log($message, 'info', 'hec', $context);

    }

    private function logError(string $message, array $context)
    {
        $this->log($message, 'error', 'error', $context);
    }

    private function log(string $message, string $type, string $name, array $context = [])
    {
        Logger::goRecord($name, $type, $message,  $context);
    }
}